#!/usr/bin/env python
import os,sys
import pexpect
"""
Name: __file__
Version: V1.0
Author: ballenwen
Description: python version of abs.sh, concurrent dispatch and control
"""

DEFAULT_TIME_OUT = 25

class pySshRsync(object):
    def __init__(self):
        """
        This program is a concurrent program with python to enrich the functions of abs.sh with shell script
        """
        self.result = {"result":0 ,"result_msg":""}
   
    def print_debug(self,pwd):
        print pwd
    def common_pexpect(self,ip,pwd,cmd,flag):
        try:
            child=pexpect.spawn(cmd)
            i=child.expect(["yes","assword:","Token"],timeout = DEFAULT_TIME_OUT)
            if i==0:
                child.sendline("yes")
                child.expect(["assword:"],timeout = DEFAULT_TIME_OUT)
            elif i==2:
                child.sendline("")
                i = child.expect(["yes","assword:"],timeout = DEFAULT_TIME_OUT)
                if i == 0:
                    child.sendline("yes")
                    i = child.expect(["yes","assword:"],timeout = DEFAULT_TIME_OUT)
                    if i == 0:
                        child.sendline("yes")
                        child.expect(["assword:"],timeout = DEFAULT_TIME_OUT)
            
            child.sendline(pwd)
            if flag == 1:
                child.expect([pexpect.EOF],timeout = DEFAULT_TIME_OUT)
            elif flag == 2:
                child.expect(["#", pexpect.EOF],timeout = DEFAULT_TIME_OUT)
            #print child.before

            if flag == 1:
                if "Timeout" in child.before:
                    tmpstr = "%s\n[SSH_RESULT_FAIL]: %s logon Timeout!\n" %(child.before,ip)                    
                    self.result['result'] = 0
                else:
                    tmpstr = "%s\n[SSH_RESULT_OK]: %s\n" %(child.before,ip)                    
                    self.result['result'] = 1                    
            elif flag == 2:
                if ("not permitted" in child.before) or ("Permission denied" in child.before) or ("rsync error" in child.before):
                    tmpstr = "%s\n[RSYNC_RESULT_FAIL]:%s\n" %(child.before,ip)                    
                    self.result['result'] = 0
                else:
                    tmpstr = "%s\n[RSYNC_RESULT_OK]:%s\n" %(child.before,ip)                    
                    self.result['result'] = 1
            self.result['result_msg'] = tmpstr
        except Exception, e:
            
            if flag == 1:
                tmpstr = "%s\n[SSH_RESULT_FAIL]:%s\n" %(child.before,ip)                
            elif flag == 2:
                tmpstr = "%s\n[RSYNC_RESULT_FAIL]:%s\n" %(child.before,ip)
            self.result['result_msg'] = tmpstr
            self.result['result'] = 0
        finally:
            child.close()
    def auto_ssh(self,ip,user,pwd,cmd):
        cmd="ssh -q -p 36000 -l %s %s %s" % (user,ip,cmd)        
        self.common_pexpect(ip,pwd,cmd,1)
        return self.result['result_msg']
    def auto_rsync_to_remote(self,ip,user,pwd,remote_path,local_path):
        cmd = "rsync -avz -e  \'/usr/local/bin/ssh -q -p 36000\' %s  %s@%s:%s"  %(local_path,user,ip,remote_path)
        self.common_pexpect(ip,pwd,cmd,2)
        return self.result
    def auto_rsync_to_local(self,ip,user,pwd,remote_path,local_path):
        cmd = "rsync -avz -e  \'/usr/local/bin/ssh -q -p 36000\' %s@%s:%s %s"  %(user,ip,remote_path,local_path)
        self.common_pexpect(ip,pwd,cmd,2)
        return self.result

if __name__ == '__main__':
    if len(sys.argv) != 5:
        print 'Usage:%s ip user pwd cmd' % sys.argv[0]
        os._exit(1)
    ip=sys.argv[1]
    user=sys.argv[2]
    pwd=sys.argv[3]
    cmd=sys.argv[4]
    obj = pySshRsync()
    #print obj.auto_ssh('10.132.131.140','Administrator','Cft@server_12','ls /cygdrive/d')
    ret=obj.auto_ssh(ip,user,pwd,cmd)
    print ret
    #obj.print_debug(pwd)
